package com.example.springboot.scheduled;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 根据调用者需求创建或者删除定时任务
 * <p>
 */
@Component
public class ScheduleTaskManual {

    public static Map<String, ScheduledFuture<?>> SCHEDULE_MAP = new ConcurrentHashMap<>();

    @Autowired
    private TaskScheduler taskScheduler;

    //添加任务
    public void addTask(String taskName, String cron){
        ScheduledFuture<?> schedule = taskScheduler.schedule(new Task(), new TriggerImpl(cron));
        System.out.println(String.format("【%s】任务已启动", taskName));
        SCHEDULE_MAP.put(taskName,schedule);
    }

    //删除任务
    public void removeTask(String taskName){
        ScheduledFuture<?> future = SCHEDULE_MAP.get(taskName);
        //判断任务是否为空或者已经结束
        if (null != future && !future.isCancelled()){
            future.cancel(true);
            while (!future.isDone()) {
                future.cancel(true);
            }
        }
        System.out.printf("【%s】任务已停止%n", taskName);
        SCHEDULE_MAP.remove(taskName);
    }



    /**
     * 测试任务
     */
    class Task  implements Runnable{
        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println(name+"----"+ LocalDateTime.now());
        }
    }

    /**
     * cron表达式
     */
    class TriggerImpl implements Trigger {

        private String cronExpress;

        public TriggerImpl(String cronExpress) {


            this.cronExpress = cronExpress;
        }


        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            CronTrigger cronTrigger = new CronTrigger(cronExpress);
            return cronTrigger.nextExecutionTime(triggerContext);
        }
    }
}
